import Crypt from "../../utils/Crypt";
import CategoryModel from "../../models/Category";
import PageModel from "../../models/Page";

const categoryModel = new CategoryModel()
const pageModel = new PageModel()

Page({
  data: {
    currentIndex: 0,
    list: []
  },

  onLoad: function (options) {
    // get data
    // pageModel.getCategory().then(response => {
    //   let { data } = response
    //   data = Crypt.parse(data)
    //   this.setData({ ...data, list: data.firstChildren })
    // })

    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline'],
      success: () => {
        // console.log('ok')
        // 可以把分享记录保存到数据库
      }
    })
  },

  onShow(options) {
    pageModel.getCategory().then(response => {
      let { data } = response
      data = Crypt.parse(data)

      // category status
      data.firstLevel = data.firstLevel.filter(x => +x.status === 1)

      this.setData({ ...data, list: data.firstChildren })
      const id = getApp().globalData.categoryIndex || 0
      if (+id > 0) {
        let index = 0
        data.firstLevel.forEach((v, i) => {
          if (v.id === id) {
            index = i
            return
          }
        })

        this.setData({ currentIndex: index })
        categoryModel.getMenuData(id).then(response => {
          let { data } = response
          data = Crypt.parse(data)
          this.setData({list: data})
        })
      }
    })
  },

  onHide() {
    this.setData({ currentIndex: 0 })
    getApp().globalData.categoryIndex = 0
  },

  onMenu(event) {
    getApp().globalData.categoryIndex = 0
    const data = event.detail.data
    const { index, id } = data
    this.setData({ currentIndex: index })
    categoryModel.getMenuData(id).then(response => {
      let { data } = response
      data = Crypt.parse(data)
      this.setData({list: data})
    })
  }

});
